package com.lighting.module3;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.NumberFormat;

@Controller
public class CalController {

    Calculator[] getCalculator(double p, int m, double yr) {
        return new Calculator[] {
                new Calculator0(p, m, yr),
                new Calculator1(p, m, yr),
                new Calculator2(p, m, yr)
        };
    }

    @RequestMapping("/cal")
    @ResponseBody
    String[] Cal(double p, int m, double yr, int type) {
        Check(p, m, yr, type);
        Calculator[] calculators = getCalculator(p, m, yr);
        Calculator c = calculators[type];
        return c.cal();
    }

    @RequestMapping("/details")
    @ResponseBody
    String[][] ShowDetails(double p, int m, double yr, int type) {
        Check(p, m, yr, type);
        Calculator[] calculators = getCalculator(p, m, yr);
        Calculator c = calculators[type];
        return c.details();
    }

    @RequestMapping("/test1")
    @ResponseBody
    String Test1(){
        return "测试1：￥ ，你好，世界！";
    }

    @RequestMapping("/test2")
    @ResponseBody
    String Test2(){
        return "测试2：￥123456 ，你好！";
    }



    /**
     * 对用户输入的参数做检查
     * @param p 本金
     * @param m 月份
     * @param yr   年利率
     * @param type 还款类型
     */
    static void Check(double p, int m, double yr, int type) {
        if (p <= 0) {
            throw new IllegalArgumentException("本金必须>0");
        }
        if (m < 1 || m > 360) {
            throw new IllegalArgumentException("贷款月份范围必须在1-360之间");
        }
        if (yr < 1 || yr > 36) {
            throw new IllegalArgumentException("年利率范围必须在1-36之间");
        }
        if (type != 0 && type != 1 && type != 2) {
            throw new IllegalArgumentException("不支持的还款类型");
        }
    }

}
